define(['WebPDF', 
	"./PageViewLayoutService",
	"../PDFApiProvider"], function(WebPDF) {
		'use strict';
	WebPDF.directive('pdfDoc', ['$compile', '$timeout', 'PageViewLayout', 'PDFApi',
		function($compile, $timeout, PageViewLayout, PDFApi) {		
		//计算页面区域占可见区域的比率，比率最大的一个认为是当前页
		function calcRatioOfPageToVisibleArea(pageElement, visibleArea) {
			var offset = pageElement.offset();
			var height = pageElement.height();

			//页面的范围
			var lowest = pageElement.offset().top;
			var highest = lowest + pageElement.height();

			//可见区域中页面的范围
			lowest = Math.max(lowest, visibleArea.top);
			highest = Math.min(highest, visibleArea.top + visibleArea.height);

			//计算比率
			return (highest - lowest) / visibleArea.height;
		}		
		
		return {
			restrict: 'AE',
			controller: 'PDFDocController',		
			link: function($scope, element, attr) {	
				$scope.scale = 1.25;		
				$scope.zoomMode = "125";	

				var watchPdfDocDestroy = $scope.$watch("pdfDoc", function(newValue, oldValue) {
					if (newValue === oldValue) return;
					console.log(newValue.pdfPages)
					watchPdfDocDestroy();	
					$scope.layout = new PageViewLayout(element, $scope.pdfDoc);
					$scope.layout.scroll(onScroll);									
				});

				var watchDestroy = $scope.$watchCollection("pdfDoc.pdfPages", function(pdfPages) {
					if (pdfPages) {
						console.log(pdfPages)
						$scope.layout.createPDFPageView(function(page){
							var newScope = $scope.$new();
							newScope.page = page;
							var compiledContents = $compile('<div pdf-page></div>');
							return compiledContents(newScope);
						});					
						watchDestroy();								
					}
				});
				
				$scope.$watchGroup(["viewerHeight", "viewerWidth", "leftPanelWidth"], function() {		
					$scope.onSize();																	
				});

				var pageCountWatchDestroy = $scope.$watch("pdfDoc.pageCount", function(newValue){
					if (newValue) {
						PDFApi.pageCountChanged({
							'pageCount': newValue
						});
						pageCountWatchDestroy();
					}
				});
				
				$scope.$watch("zoomMode", function(newValue, oldValue) {
					if (!newValue) return;											
					PDFApi.scaleChanged({scale: $scope.zoomMode});					
				});

				$scope.$on("setScale", function(event, data){					
					if (!$scope.layout) return;
					var scale = $scope.layout.calcScale(data.zoomMode);	
					if (!scale)	return;
					$scope.$apply(function(scope){
						$scope.scale = scale;						
					});		

					if (data.zoomMode === "FitPage"){						
						gotoPage($scope.curPageIndex, true, true);					
					}					
					$scope.layout.setScale($scope.scale);				
				});

				$scope.$on("gotoPage", function(event, data){		
					gotoPage(data.pageIndex);
				});			

				$scope.$on("nextPage", function(event, data){		
					gotoPage($scope.curPageIndex+1);
				});						

				$scope.$on("previousPage", function(event, data){		
					gotoPage($scope.curPageIndex-1);
				});	
				
				
				var onScroll = _.throttle(function() {					
					var curPageIndex;
					var maxRatio = 0;
					$scope.layout.getContentPane().children().each(function(index) {
						var _self = $(this);
						if (!_self.attr("pageIndex")) return;
						var ratio = calcRatioOfPageToVisibleArea(_self, $scope.docVisibleArea);
						//页面滚动可见区域时生成具体的页面								
						if (ratio > 0) {								
							_self.trigger("page-visible-changed", [{'visible': true}]);			
							_self.trigger("loadpage");							
						}
						else{
							_self.trigger("page-visible-changed", [{'visible': false}]);
						}
						if (ratio > maxRatio) {
							maxRatio = ratio;
							curPageIndex = parseInt(_self.attr("pageIndex"));
						}
					});
					if ($scope.curPageIndex !== curPageIndex) {
						$scope.curPageIndex = curPageIndex;
						PDFApi.curPageChanged({
							'curIndex': curPageIndex
						});
					}
				}, 1000);		
			
				$scope.onSize = function() {
					if (typeof $scope.leftPanelWidth == 'undefined') return;					

					var offsetLeft = $scope.leftPanelWidth;
					var docViewWidth = $scope.viewerWidth - offsetLeft;
					var docViewHeight = $scope.viewerHeight;

					element.css({
						'width': docViewWidth,
						'height': docViewHeight,
						'left': offsetLeft,
						'top': 0
					});

					$scope.docViewWidth = docViewWidth;
					$scope.docViewHeight = docViewHeight;												
					$scope.docVisibleArea = calcVisibleArea();		
					if ($scope.layout) $scope.layout.reSize();		
				};			

				function gotoPage (pageIndex){
					if (pageIndex < 0 || pageIndex > $scope.pdfDoc.pageCount - 1) return;				
					$scope.curPageIndex = pageIndex;		
					$scope.layout.gotoPage(pageIndex);			
					
				}
				function calcVisibleArea() {
					var docRange = element.offset();
					docRange.width = element.width();
					docRange.height = element.height();
					return docRange;					
				}	

				element.on("movePage", function(event, offsetX, offsetY) {
					$scope.layout.movePage(offsetX, offsetY);
				});

				WebPDF.PageContainerCreated({'pageContainer': element});
			}
		};
	}]);
});